﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using AMS.Database;
using AMS.Business;
using AMS.UI;

namespace AMS
{
    public partial class frmRequest : BaseForm, IUpdatableForm
    {
        private RequestClass request;
        private Int32 _requestNumber = -1;
        private List<RequestorClass> requestorList;

        #region Form events

        public frmRequest(Int32 requestNumber)
        {
            InitializeComponent();

            try
            {
                base.isSingleton = false;

                request = new RequestClass();
                _requestNumber = requestNumber;
                
                // Fill al the lists
                FillRequestors();
                FillAvailableAnalysisMethods();

                if (requestNumber != -1)
                {
                    request.Load(requestNumber);
                    LoadRequest();
                }

                lblRequestNumber.Text = request.RequestNumber.ToString();
                lblStatus.Text = request.Status.ToString();
                txtGlass.Text = request.Glass;
                txtLinen.Text = request.Linnen;
                txtPaper.Text = request.Paper;
                txtPlastic.Text = request.Plastic;

                SetFormText();

                if (request.IsNew)
                {
                    btnSave.Enabled = false;
                }
                else
                {
                    btnSave.Enabled = true;
                }

                // TODO: Focus zetten op nieuwe combobox; redelijke simpel
                cboRequestors.Focus();
            }
            catch (Exception ex)
            {
                base.internalFormManager.ShowError(ex);
            }
        }

        #endregion

        #region Lists

        private void FillRequestors()
        {
            requestorList = DataAccess.GetRequestorList();

            cboRequestors.DataSource = null;
            cboRequestors.DataSource = requestorList;
            cboRequestors.DisplayMember = "RequestorName";
            cboRequestors.ValueMember = "RequestorID";

            if (_requestNumber != -1)
            {
                cboRequestors.SelectedValue = _requestNumber;
            }
        }

        private void FillAvailableAnalysisMethods()
        {
            chklstAvailableAnalysisMethods.DataSource = null;
            chklstAvailableAnalysisMethods.DataSource = DataAccess.GetAvailableAnalysisMethodList();
            chklstAvailableAnalysisMethods.DisplayMember = "AnalysisMethodName";
            chklstAvailableAnalysisMethods.ValueMember = "AnalysisMethodID";
            chklstAvailableAnalysisMethods.SelectedIndex = -1;

            if (request.RequestNumber != 0)
            {
                SetSelectedAnalysisMethods();
            }
            else
            {
                request.ClearAnalysisMethod();
            }
        }

        #endregion

        #region Input and Validation
        private void Input_Validating(object sender, CancelEventArgs e)
        {
            Control currentControl = (Control)sender;
            try
            {
                String controlName = currentControl.Name;
                switch (controlName)
                {
                    case "txtPaper":
                        request.Paper = currentControl.Text;
                        break;
                    case "txtGlass":
                        request.Glass = currentControl.Text;
                        break;
                    case "txtLinen":
                        request.Linnen = currentControl.Text;
                        break;
                    case "txtPlastic":
                        request.Plastic = currentControl.Text;
                        break;
                    case "txtProduct":
                        request.Product = currentControl.Text;
                        break;
                    case "txtReference":
                        request.References = currentControl.Text;
                        break;
                    case "txtSeals":
                        request.Seals = currentControl.Text;
                        break;
                    case "txtWeight":
                        request.Weight = currentControl.Text;
                        break;
                    case "txtDroppedOffBy":
                        request.DroppedOffBy = currentControl.Text;
                        break;
                }

                SetFormText();
                errRequests.SetError(currentControl, "");
                btnSave.Enabled = true;
            }
            catch (Exception ex)
            {
                HandleValidationException(currentControl, ex.Message);
            }
        }

        private void SetFormText()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("Aanvraag");
            if (request.RequestNumber != 0)
            {
                builder.Append(" - ");
                builder.Append(request.RequestNumber.ToString());
            }
            if (request.IsDirty)
            {
                builder.Append("*");
            }

            this.Text = builder.ToString();
        }

        private void RequestorSelectionChanged(object sender, EventArgs e)
        {
            Int32 selectedValue;
            String selectedName;
            String requestorDetails;

            if (cboRequestors.SelectedIndex != -1)
            {
                RequestorClass requestorClass = requestorList[cboRequestors.SelectedIndex];

                selectedValue = Convert.ToInt32(requestorClass.RequestorID);
                selectedName = requestorClass.RequestorName;
                requestorDetails = requestorClass.Details;

                request.Requestor = selectedValue;
                cboRequestors.SelectedText = selectedName;

                tip.Show(requestorDetails, cboRequestors);
            }
            else
            {
                selectedValue = -1;
                selectedName = String.Empty;
                tip.RemoveAll();
            }

            SetFormText();
        }

        private void ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (e.Index != -1)
            {
                AnalysisMethodUIClass view = (AnalysisMethodUIClass)chklstAvailableAnalysisMethods.Items[e.Index];

                Int32 value = view.AnalysisMethodID;

                if (e.NewValue == CheckState.Checked)
                {
                    request.AddAnalysisMethod(value);
                }
                else
                {
                    request.RemoveAnalysisMethod(value);
                }

                SetFormText();
            }
        }
        #endregion

        #region Error handling
        private void HandleValidationException(Control currentControl, String value)
        { 
            errRequests.SetError(currentControl, value);
            currentControl.Focus();
            btnSave.Enabled = false;
        }
        #endregion

        #region Button Events
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                request.Save();
                lblRequestNumber.Text = request.RequestNumber.ToString();

                SetFormText();

                base.internalFormManager.RefreshData(this);
            }
            catch (Exception ex)
            {
                base.internalFormManager.ShowError(ex);
            }
        }
        
        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dialogResult = MessageBox.Show("Ben je zeker dat je de aanvraag wil verwijderen?", "Verwijderen aanvraag", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (dialogResult == DialogResult.Yes)
                {
                    request.Delete();
                    base.internalFormManager.RefreshData(this);
                    this.Close();   
                }
            }
            catch (Exception ex)
            {
                base.internalFormManager.ShowError(ex);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            base.internalFormManager.DestroyForm(this);
        }
        #endregion

        #region Load
        private void LoadRequest()
        {
            txtDroppedOffBy.Text = request.DroppedOffBy;
            txtGlass.Text = request.Glass;
            txtLinen.Text = request.Linnen;
            txtPaper.Text = request.Paper;
            txtPlastic.Text = request.Plastic;
            txtProduct.Text = request.Product;
            txtReference.Text = request.References;
            txtWeight.Text = request.Weight;
            txtSeals.Text = request.Seals;
            dateInstructions.Value = request.InstructionsReceived;
            dateRequest.Value = request.SampleReceived;

            // TODO: hier moeten we ook iets forceren
            cboRequestors.SelectedValue = request.Requestor;

            SetSelectedAnalysisMethods();
        }

        private void SetSelectedAnalysisMethods()
        {
            // Clear all the selected items
            chklstAvailableAnalysisMethods.ClearSelected();

            // Go through all the analysis methods
            //ListBox.ObjectCollection items = lstAvaillableAnalysisMethods.Items;
            ListBox.ObjectCollection items = chklstAvailableAnalysisMethods.Items;

            List<AnalysisMethodUIClass> selectedAnalysisMethods = request.AnalysisMethods;
            for (int i = 0; i < selectedAnalysisMethods.Count; i++)
            {
                AnalysisMethodUIClass currentSelectedItem = selectedAnalysisMethods[i];

                for (int j = 0; j < items.Count; j++)
                {
                    AnalysisMethodUIClass view = (AnalysisMethodUIClass)items[j];

                    if (currentSelectedItem.AnalysisMethodID == view.AnalysisMethodID)
                    {
                        // The j counter is the index of the item in the list box
                        //lstAvaillableAnalysisMethods.SetSelected(j, true);
                        chklstAvailableAnalysisMethods.SetItemChecked(j, true);
                    }
                }
            }
        }
        #endregion

        #region IUpdatableForm Members

        public void RefreshData()
        {
            FillAvailableAnalysisMethods();
            FillRequestors();
        }

        #endregion
    }
}
